package mail.fetch.m21cn;

import com.han.http.client.method.BaseHttpRequest;
import com.han.http.client.method.HttpGet;
import com.han.http.client.paramter.FormDataPair;
import com.han.http.client.paramter.RequestHeader;
import com.han.http.fetch.Fetcher;
import mail.util.CookieParser;
import mail.util.JsInvoker;
import mail.verify.chaojiying.PCodeUtil;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.han.http.util.Print.printlnInfo;

@Deprecated
public class Login {
    private String username;
    private String password;
    private Map<String, String> cookieRepository;
    private Fetcher fetcher;

    Login(String username, String password) {
        this.username = username;
        this.password = password;
        cookieRepository = new HashMap<>();
        fetcher = new Fetcher();
    }

    public static void main(String... args) {
        Login login = new Login("tianlangqiqing@21cn.com", "huifenghechang1.");
        printlnInfo(login.encrypt("dhb123456.", "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDY7mpaUysvgQkbp0iIn2ezoUyhi1zPFn0HCXloLFWT7uoNkqtrphpQ/63LEcPz1VYzmDuDIf3iGxQKzeoHTiVMSmW6FlhDeqVOG094hFJvZeK4OzA6HVwzwnEW5vIZ7d+u61RV1bsFxmB68+8JXs3ycGcE4anY+YzZJcyOcEGKVQIDAQAB"));
    }

    public Map<String, String> getCookieRepository() throws Exception {
        String reportRestUrl = w2();
        reportRest(reportRestUrl);
        String redirectedUrl = unifyLogin();
        unifyAccountLogin(redirectedUrl);
        analysis();
        netCaptcha(redirectedUrl);
        byte[] imageBytes = picCaptcha(redirectedUrl);
        String verificationCode = PCodeUtil.getVerificationCode("1902", imageBytes, "ttttest");
        String toUrl = loginSubmit(redirectedUrl, verificationCode);
        loginReturn(toUrl);

        return cookieRepository;
    }

    private String w2() throws Exception {
        String url = "http://mail.21cn.com/w2/";
        RequestHeader[] requestHeaders = {
                new RequestHeader("Host", "mail.21cn.com"),
                new RequestHeader("Connection", "keep-alive"),
                new RequestHeader("Cache-Control", "max-age=0"),
                new RequestHeader("Upgrade-Insecure-Requests", "1"),
                new RequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36"),
                new RequestHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8"),
                new RequestHeader("Accept-Encoding", "gzip, deflate"),
                new RequestHeader("Accept-Language", "zh-CN,zh;q=0.9"),
        };
        Map<String, List<String>> map = fetcher.getAllInfoByGet(url, requestHeaders, 1000 * 3, 1000 * 3, true, null);
        String pageContent = map.get("page-content").get(0);
        String reportRestUrl = pageContent.substring(pageContent.indexOf("/api/htmlReportRest/getJs.js"));
        reportRestUrl = reportRestUrl.substring(0, reportRestUrl.indexOf("';"));
        CookieParser.parseList(cookieRepository, map.get("Set-Cookie"));
        String accessId = pageContent.substring(pageContent.indexOf("7moorInit.js?accessId=") + 22);
        accessId = accessId.substring(0, accessId.indexOf("&autoShow"));
        cookieRepository.put("accessId", accessId);

        return reportRestUrl;
    }

    private void reportRest(String reportRestUrl) throws Exception {
        String url = "http://ux.21cn.com" + reportRestUrl;
        RequestHeader[] requestHeaders = {
                new RequestHeader("Host", "ux.21cn.com"),
                new RequestHeader("Connection", "keep-alive"),
                new RequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36"),
                new RequestHeader("Accept", "*/*"),
                new RequestHeader("Referer", "http://mail.21cn.com/w2/"),
                new RequestHeader("Accept-Encoding", "gzip, deflate"),
                new RequestHeader("Accept-Language", "zh-CN,zh;q=0.9"),
        };
        Map<String, List<String>> map = fetcher.getAllInfoByGet(url, requestHeaders, 1000 * 3, 1000 * 3, true, null);
        CookieParser.parseList(cookieRepository, map.get("Set-Cookie"));
    }

    private String unifyLogin() throws Exception {
        String url = "http://mail.21cn.com/w2/logon/UnifyLogin.do?t=" + System.currentTimeMillis();
        RequestHeader[] requestHeaders = {
                new RequestHeader("Host", "mail.21cn.com"),
                new RequestHeader("Connection", "keep-alive"),
                new RequestHeader("Upgrade-Insecure-Requests", "1"),
                new RequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36"),
                new RequestHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8"),
                new RequestHeader("Referer", "http://mail.21cn.com/w2/"),
                new RequestHeader("Accept-Encoding", "gzip, deflate"),
                new RequestHeader("Accept-Language", "zh-CN,zh;q=0.9"),
                new RequestHeader("Cookie", "JSESSIONID=" + cookieRepository.get("JSESSIONID")),
        };
        Map<String, List<String>> map = fetcher.getAllInfoByGet(url, requestHeaders, 1000 * 3, 1000 * 3, true, null);
        CookieParser.parseList(cookieRepository, map.get("Set-Cookie"));
        return map.get("Location").get(0);
    }

    private void unifyAccountLogin(String url) throws Exception {
        RequestHeader[] requestHeaders = {
                new RequestHeader("Upgrade-Insecure-Requests", "1"),
                new RequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36"),
                new RequestHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8"),
                new RequestHeader("Accept-Encoding", "gzip, deflate, br"),
                new RequestHeader("Accept-Language", "zh-CN,zh;q=0.9"),
        };
        Map<String, List<String>> map = fetcher.getAllInfoByGet(url, requestHeaders, 1000 * 3, 1000 * 3, true, null);
        //从返回的字符串中获取captchaToken
        String pageContent = map.get("page-content").get(0);
        String token = pageContent.substring(pageContent.indexOf("/api/logbox/oauth2/picCaptcha.do?token=") + 39);
        token = token.substring(0, token.indexOf("&rnd="));
        cookieRepository.put("captchaToken", token);
        String rsaKey = pageContent.substring(pageContent.indexOf("j_rsaKey\" value=\"") + 17);
        rsaKey = rsaKey.substring(0, rsaKey.indexOf("\""));
        cookieRepository.put("rsaKey", rsaKey);
        //解析cookie
        CookieParser.parseList(cookieRepository, map.get("Set-Cookie"));
    }

    private void analysis() throws Exception {
        String url = "http://user-analysis.7moor.com/service?action=page.load&data=%7B%22userId%22%3Anull%2C%22sessionId%22%3Anull%2C%22account%22%3A%22N00000011127%22%2C%22accessId%22%3A%22" + cookieRepository.get("accessId") + "%22%2C%22platform%22%3A%7B%22browserName%22%3A%22Chrome%22%2C%22browserVersion%22%3A%2271.0.3578.98%22%2C%22osInfo%22%3A%22Windows%2010%2064-bit%22%2C%22platformDescription%22%3A%22Chrome%2071.0.3578.98%20on%20Windows%2010%2064-bit%22%2C%22seosource%22%3A%22%E7%AB%99%E5%86%85%22%2C%22seokeywords%22%3A%22%22%7D%2C%22page%22%3A%7B%22title%22%3A%2221CN%E4%B8%AA%E4%BA%BA%E9%82%AE%E7%AE%B1%22%2C%22prevUrl%22%3A%22%22%2C%22currentUrl%22%3A%22http%3A%2F%2Fmail.21cn.com%2Fw2%2F%22%7D%2C%22type%22%3A%22load%22%2C%22isOpenChat%22%3Afalse%2C%22rootDomain%22%3A%2221cn.com%22%7D&callback=ubaGetCallback";
        RequestHeader[] requestHeaders = {
                new RequestHeader("Host", "user-analysis.7moor.com"),
                new RequestHeader("Connection", "keep-alive"),
                new RequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36"),
                new RequestHeader("Accept", "*/*"),
                new RequestHeader("Referer", "http://mail.21cn.com/w2/"),
                new RequestHeader("Accept-Encoding", "gzip, deflate"),
                new RequestHeader("Accept-Language", "zh-CN,zh;q=0.9"),
        };
        Map<String, List<String>> map = fetcher.getAllInfoByGet(url, requestHeaders, 1000 * 3, 1000 * 3, true, null);
        String pageContent = map.get("page-content").get(0);
        String pageId = pageContent.substring(pageContent.indexOf("pageId\":\"") + 9);
        pageId = pageId.substring(0, pageId.indexOf("\",\""));
        cookieRepository.put("pageId", pageId);
        String userId = pageContent.substring(pageContent.indexOf("userId\":\"") + 9);
        userId = userId.substring(0, userId.indexOf("\",\""));
        cookieRepository.put("userId", userId);
        String sessionId = pageContent.substring(pageContent.indexOf("sessionId\":\"") + 12);
        sessionId = sessionId.substring(0, sessionId.indexOf("\",\""));
        cookieRepository.put("sessionId", sessionId);
    }

    private void netCaptcha(String referUrl) throws Exception {
        String url = "https://open.e.189.cn/api/logbox/oauth2/needcaptcha.do";
        RequestHeader[] requestHeaders = {
                new RequestHeader("Host", "open.e.189.cn"),
                new RequestHeader("Connection", "keep-alive"),
                new RequestHeader("Content-Length", "67"),
                new RequestHeader("Accept", "application/json, text/javascript, */*; q=0.01"),
                new RequestHeader("Origin", "https://open.e.189.cn"),
                new RequestHeader("X-Requested-With", "XMLHttpRequest"),
                new RequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36"),
                new RequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"),
                new RequestHeader("Referer", referUrl),
                new RequestHeader("Accept-Encoding", "gzip, deflate, br"),
                new RequestHeader("Accept-Language", "zh-CN,zh;q=0.9"),
                new RequestHeader("Cookie", "GUID=" + cookieRepository.get("GUID") + "; pageOp=" + cookieRepository.get("pageOp") + "; JSESSIONID=" + cookieRepository.get("JSESSIONID")),
        };
        FormDataPair[] formDataPairs = {
                new FormDataPair("accountType", "02"),
                new FormDataPair("userName", username),
                new FormDataPair("appKey", "8013411507")
        };
        fetcher.getAllInfoByPost(url, requestHeaders, formDataPairs, 1000 * 3, 1000 * 3, true, null);
    }

    private byte[] picCaptcha(String referUrl) throws Exception {
        String url = "https://open.e.189.cn/api/logbox/oauth2/picCaptcha.do?token=" + cookieRepository.get("captchaToken") + "&rnd=" + System.currentTimeMillis();
        RequestHeader[] requestHeaders = {
                new RequestHeader("Host", "open.e.189.cn"),
                new RequestHeader("Connection", "keep-alive"),
                new RequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36"),
                new RequestHeader("Accept", "image/webp,image/apng,image/*,*/*;q=0.8"),
                new RequestHeader("Referer", referUrl),
                new RequestHeader("Accept-Encoding", "gzip, deflate, br"),
                new RequestHeader("Accept-Language", "zh-CN,zh;q=0.9"),
                new RequestHeader("Cookie", "GUID=" + cookieRepository.get("GUID") + "; pageOp=" + cookieRepository.get("pageOp") + "; JSESSIONID=" + cookieRepository.get("JSESSIONID")),
        };

        HttpGet httpGet = BaseHttpRequest.getGetMethod(url);
        httpGet.setConnectTimeout(1000 * 3);
        httpGet.setReadTimeout(1000 * 3);
        httpGet.setHeaders(requestHeaders);
        httpGet.execute();
        return httpGet.getBytes();
    }

    private String loginSubmit(String referUrl, String v) throws Exception {
        String url = "https://open.e.189.cn/api/logbox/oauth2/loginSubmit.do";
        RequestHeader[] requestHeaders = {
                new RequestHeader("Host", "open.e.189.cn"),
                new RequestHeader("Connection", "keep-alive"),
                new RequestHeader("Content-Length", "599"),
                new RequestHeader("Accept", "application/json, text/javascript, */*; q=0.01"),
                new RequestHeader("Origin", "https://open.e.189.cn"),
                new RequestHeader("X-Requested-With", "XMLHttpRequest"),
                new RequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36"),
                new RequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"),
                new RequestHeader("Referer", referUrl),
                new RequestHeader("Accept-Encoding", "gzip, deflate, br"),
                new RequestHeader("Accept-Language", "zh-CN,zh;q=0.9"),
                new RequestHeader("Cookie", "GUID=" + cookieRepository.get("GUID") + "; pageOp=" + cookieRepository.get("pageOp") + "; JSESSIONID=" + cookieRepository.get("JSESSIONID")),
        };
        /*ImageIcon img = new ImageIcon(imageByte);
        JLabel label = new JLabel(img);
        String v = JOptionPane.showInputDialog(label);*/
        String encodePwd = encrypt(password, cookieRepository.get("rsaKey"));//Selenium.mail21CNEncode(password, cookieRepository.get("rsaKey"));
        FormDataPair[] formDataPairs = {
                new FormDataPair("appKey", "8013411507"),
                new FormDataPair("accountType", "02"),
                new FormDataPair("userName", username),
                new FormDataPair("password", encodePwd),
                new FormDataPair("validateCode", v),
                new FormDataPair("captchaToken", cookieRepository.get("captchaToken")),
                new FormDataPair("returnUrl", "http%3A%2F%2Fmail.21cn.com%2Fw2%2Flogon%2FunifyPlatformLogonReturn.do%3FLSID%3D" + cookieRepository.get("LSID")),
                new FormDataPair("mailSuffix", ""),
                new FormDataPair("dynamicCheck", "FALSE"),
                new FormDataPair("clientType", "10010"),
                new FormDataPair("cb_SaveName", "0"),
                new FormDataPair("isOauth2", "false"),
                new FormDataPair("state", ""),
        };
        Map<String, List<String>> map = fetcher.getAllInfoByPost(url, requestHeaders, formDataPairs, 1000 * 3, 1000 * 3, true, null);
        printlnInfo(map);
        String pageContent = map.get("page-content").get(0);
        String toUrl = pageContent.substring(pageContent.indexOf("\"toUrl\":\"") + 9);
        toUrl = toUrl.substring(0, toUrl.indexOf("\""));

        return toUrl;
    }

    private void loginReturn(String toUrl) throws Exception {
        String cookie = "JSESSIONID=" + cookieRepository.get("LSID") +
                ";LSID=" + cookieRepository.get("LSID") +
                ";apm_ct=" + cookieRepository.get("apm_ct") +
                ";apm_sid=" + cookieRepository.get("apm_sid") +
                ";apm_uid=" + cookieRepository.get("apm_uid") +
                ";apm_ip=" + cookieRepository.get("apm_ip") +
                ";apm_ua=" + cookieRepository.get("apm_ua") +
                ";qimo_seosource_ef9e5f30-ed02-11e6-8921-5bf6fce3cd5e=" + "%E7%AB%99%E5%86%85" +
                ";qimo_seokeywords_ef9e5f30-ed02-11e6-8921-5bf6fce3cd5e=" +
                ";href=http%3A%2F%2Fmail.21cn.com%2Fw2%2F" +
                //";accessId=" + cookieRepository.get("accessId") +
                ";pageViewNum=1";// +
        //";bad_idef9e5f30-ed02-11e6-8921-5bf6fce3cd5e=" + cookieRepository.get("userId") +
        //";nice_idef9e5f30-ed02-11e6-8921-5bf6fce3cd5e=" + cookieRepository.get("sessionId");
        RequestHeader[] requestHeaders = {
                new RequestHeader("Host", "mail.21cn.com"),
                new RequestHeader("Connection", "keep-alive"),
                new RequestHeader("Upgrade-Insecure-Requests", "1"),
                new RequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36"),
                new RequestHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8"),
                new RequestHeader("Accept-Encoding", "gzip, deflate"),
                new RequestHeader("Accept-Language", "zh-CN,zh;q=0.9"),
                new RequestHeader("Cookie", cookie),
        };
        Map<String, List<String>> map = fetcher.getAllInfoByGet(toUrl, requestHeaders, 1000 * 3, 1000 * 3, false, null);
        CookieParser.parseList(cookieRepository, map.get("Set-Cookie"));
    }

    private String encrypt(String pwd, String rsaKey) {
        String filePath = "F:\\workspace\\java\\MailCrawler\\src\\main\\resources\\Encrypt21CN.js";
        String method = "encode('" + pwd + "','" + rsaKey + "')";

        return "{RSA}" + JsInvoker.invokeJs(method, filePath);
    }
}